package com.xyh.reward_kotlin.fragments

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.util.Patterns
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
import com.xyh.reward_kotlin.R
import com.xyh.reward_kotlin.api.ApiCallback
import com.xyh.reward_kotlin.api.ApiClient
import com.xyh.reward_kotlin.api.RewardApi
import com.xyh.reward_kotlin.response.ResultDto
import com.xyh.reward_kotlin.response.UserDto
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.Calendar

class ProfileFragment : Fragment(R.layout.fragment_profile) {

    private var imageAvatar: ImageView? = null
    private var textNickname: TextView? = null
    private var textEmail: TextView? = null
    private var textBirthday: TextView? = null
    private var btnEdit: Button? = null

    private var id: Long? = 1L
    private var nickname: String? = "小明"
    private var email: String? = "example@email.com"
    private var birthday: String? = "2000-01-01"
    private val rewardApi: RewardApi = ApiClient.client.create(RewardApi::class.java)

    private lateinit var pickImageLauncher: ActivityResultLauncher<String>
    private lateinit var permissionLauncher: ActivityResultLauncher<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 注册选择图片
        pickImageLauncher =
            registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
                Log.d("profile", "GetContent result uri: $uri")
                uri?.let {
                    try {
                        val localFile = copyUriToInternalStorage(it)
                        Log.d("profile", "头像已复制至: ${localFile.absolutePath}")
                        saveDbAvatar(localFile)
                        saveAvatarPath(localFile.absolutePath)
                        val bitmap = BitmapFactory.decodeFile(localFile.absolutePath)
                        imageAvatar?.setImageBitmap(bitmap)
                    } catch (e: IOException) {
                        Log.e("profile", "头像保存失败: ${e.message}")
                        Toast.makeText(context, "头像保存失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }

        // 注册权限申请
        permissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
                Log.d("profile", "权限请求结果: $isGranted")
                if (isGranted) {
                    pickImageLauncher.launch("image/*")
                } else {
                    Toast.makeText(context, "没有读取媒体的权限", Toast.LENGTH_SHORT).show()
                }
            }
    }

    private fun saveDbAvatar(file: File) {
        Log.d("profile", "准备上传头像: ${file.absolutePath}, 大小: ${file.length()}")
        val requestFile = RequestBody.create("image/png".toMediaTypeOrNull(), file)
        val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
        val userId = RequestBody.create("text/plain".toMediaTypeOrNull(), id.toString())

        rewardApi.updateAvatar(body, userId).enqueue(object : ApiCallback<ResultDto<Int>>() {
            override fun onSuccess(result: ResultDto<Int>) {
                Log.d("profile", "数据库头像数据更新成功: $result")
                Toast.makeText(context, "数据库头像数据更新成功！", Toast.LENGTH_SHORT).show()
            }

            override fun onError(errorMsg: String?) {
                Log.e("profile", "数据库头像数据更新失败！$errorMsg")
                Toast.makeText(context, "数据库头像数据更新失败！", Toast.LENGTH_SHORT).show()
            }
        })
    }

    @Throws(IOException::class)
    private fun copyUriToInternalStorage(uri: Uri): File {
        val file = File(requireContext().filesDir, "avatar.jpg")
        Log.d("profile", "准备复制头像到: ${file.absolutePath}")
        requireContext().contentResolver.openInputStream(uri).use { input ->
            FileOutputStream(file).use { output ->
                input?.copyTo(output)
            }
        }
        Log.d("profile", "头像复制完成")
        return file
    }

    private fun saveAvatarPath(path: String) {
        Log.d("profile", "保存头像路径到SP: $path")
        requireContext().getSharedPreferences("profile", Context.MODE_PRIVATE)
            .edit {
                putString("avatar_path", path)
            }
    }

    private fun loadAvatarPath(): String? {
        val path = requireContext().getSharedPreferences("profile", Context.MODE_PRIVATE)
            .getString("avatar_path", null)
        Log.d("profile", "加载本地头像路径: $path")
        return path
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        imageAvatar = view.findViewById(R.id.image_avatar)
        textNickname = view.findViewById(R.id.text_nickname)
        textEmail = view.findViewById(R.id.text_email)
        textBirthday = view.findViewById(R.id.text_birthday)
        btnEdit = view.findViewById(R.id.btn_edit)

        loadProfile(view)

        // 加载本地头像
        loadAvatarPath()?.let { path ->
            val avatarFile = File(path)
            if (avatarFile.exists()) {
                Log.d("profile", "本地头像存在, 加载: $path")
                imageAvatar?.setImageURI(Uri.fromFile(avatarFile))
            } else {
                Log.w("profile", "本地头像文件不存在: $path")
            }
        }

        imageAvatar?.setOnClickListener { checkPermissionAndSelectImage() }
        btnEdit?.setOnClickListener { showEditDialog() }
    }

    private fun checkPermissionAndSelectImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Log.d("profile", "检查READ_MEDIA_IMAGES权限")
            if (ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.READ_MEDIA_IMAGES
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionLauncher.launch(Manifest.permission.READ_MEDIA_IMAGES)
            } else {
                pickImageLauncher.launch("image/*")
            }
        } else {
            Log.d("profile", "检查READ_EXTERNAL_STORAGE权限")
            if (ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
            } else {
                pickImageLauncher.launch("image/*")
            }
        }
    }

    private fun loadProfile(view: View) {
        Log.d("profile", "开始加载用户资料")
        rewardApi.getProfile().enqueue(object : ApiCallback<UserDto>() {
            override fun onSuccess(result: UserDto) {
                Log.d("profile", "资料接口返回: $result")
                result.let {
                    id = it.id
                    email = it.mail
                    nickname = it.nickName
                    if (it.birthday != null) {
                        birthday = it.birthday
                    }
                    updateUI()
                }
            }

            override fun onError(errorMsg: String?) {
                Log.e("profile", "资料接口调用失败: $errorMsg")
                Snackbar.make(view, "加载个人信息数据失败：$errorMsg", Snackbar.LENGTH_LONG).show()
            }
        })
    }

    @SuppressLint("SetTextI18n")
    private fun updateUI() {
        Log.d("profile", "开始更新UI: 昵称=$nickname, 邮箱=$email, 生日=$birthday")
        textNickname?.text = "昵称：$nickname"
        textEmail?.text = "邮箱：$email"
        textBirthday?.text = "生日：$birthday"
    }

    private fun showEditDialog() {
        val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_edit_profile, null)
        val editNickname: EditText = dialogView.findViewById(R.id.edit_nickname)
        val editEmail: EditText = dialogView.findViewById(R.id.edit_email)
        val editBirthday: EditText = dialogView.findViewById(R.id.edit_birthday)

        // 初始化已有数据
        editNickname.setText(nickname)
        editEmail.setText(email)
        editBirthday.setText(birthday)

        editBirthday.setOnClickListener {
            val calendar = Calendar.getInstance()
            if (!editBirthday.text.isNullOrEmpty()) {
                val parts = editBirthday.text.toString().split("-")
                if (parts.size == 3) {
                    calendar.set(parts[0].toInt(), parts[1].toInt() - 1, parts[2].toInt())
                }
            }
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH)
            val day = calendar.get(Calendar.DAY_OF_MONTH)

            DatePickerDialog(requireContext(), { _, y, m, d ->
                val monthStr = (m + 1).toString().padStart(2, '0')
                val dayStr = d.toString().padStart(2, '0')
                editBirthday.setText("$y-$monthStr-$dayStr")
            }, year, month, day).show()
        }

        AlertDialog.Builder(requireContext())
            .setTitle("编辑资料")
            .setView(dialogView)
            .setPositiveButton("保存") { _, _ ->
                val newNickname = editNickname.text.toString().trim()
                val newEmail = editEmail.text.toString().trim()
                val newBirthday = editBirthday.text.toString().trim()

                if (newNickname.isEmpty()) {
                    Log.w("profile", "昵称为空")
                    Toast.makeText(context, "昵称不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                if (!isValidEmail(newEmail)) {
                    Log.w("profile", "邮箱格式不正确: $newEmail")
                    Toast.makeText(context, "邮箱格式不正确", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }

                nickname = newNickname
                email = newEmail
                birthday = newBirthday
                updateUI()

                val userDto = UserDto().apply {
                    id = this@ProfileFragment.id
                    nickName = nickname
                    mail = email
                    birthday = newBirthday
                }
                Log.d("profile", "准备提交更新: $userDto")

                rewardApi.updateProfile(userDto).enqueue(object : ApiCallback<UserDto>() {
                    override fun onSuccess(result: UserDto) {
                        Log.d("profile", "资料已更新: $result")
                        Toast.makeText(context, "资料已更新", Toast.LENGTH_SHORT).show()
                    }

                    override fun onError(errorMsg: String?) {
                        Log.e("profile", "资料更新失败: $errorMsg")
                        Toast.makeText(context, "资料更新失败！", Toast.LENGTH_SHORT).show()
                    }
                })
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun isValidEmail(email: String): Boolean {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches()
    }
}